<template>
	<view class="content" style="padding: 30rpx;">
		<u-form :model="form" ref="uForm" :labelStyle="{fontSize: '28rpx', color: 'rgba(0, 0, 0, 0.8)'}">

			<u-form-item label-width="150" label="场地" required borderBottom @click="showMerchantStorePicker"
				:arrow="true">
				<u--input v-model="form.storeName" input-align="right" disabled disabledColor="#ffffff"
					placeholder="请选择经营场地" border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
				<!-- merchantStoreColumns merchantStoreSelectIsShow merchantStoreName  merchantStoreConfirm-->
				<u-popup :round="10" mode="center" :show="merchantStoreSelectIsShow" @close="close()" :closeable="true"
					:safeAreaInsetBottom="false" :closeOnClickOverlay="true">
					<view style="padding:30rpx">
						<view class="select-store-title">请选择场地</view>
						<scroll-view style="height:600rpx;" v-if="merchantStoreList.length>0" scroll-y="true"
							:scroll-with-animation="true" :enable-back-to-top="true" @scrolltolower="reachBottom">
							<u-radio-group placement="column" v-model="merchantStoreName">
								<u-radio v-for="(item, indexModal) in merchantStoreList" :key="indexModal"
									:label="item.storeName" :name="item.storeName" activeColor="#6072FF"
									@change="merchantStoreChange(indexModal)">
									<view class="model-item" @click="merchantStoreChange(indexModal)">
										<view class="model-set">
											{{item.storeName}}
										</view>
										<u-line></u-line>
									</view>
								</u-radio>
							</u-radio-group>
							<view>
								<u-loadmore v-if="merchantStoreList.length == 0" :status="status" load-text="暂无场地" />
							</view>
						</scroll-view>
						<view style="display: flex;justify-content: space-between;">
							<u-button type="primary" @click="navToStoreManage"
								:customStyle="{width: '250rpx', height: '70rpx', borderRadius: '20rpx', margin:'20rpx'}"
								text="添加场地"></u-button>
							<u-button type="primary" @click="merchantStoreConfirm"
								:customStyle="{width: '250rpx', height: '70rpx', borderRadius: '20rpx', margin:'20rpx'}"
								text="确认选择"></u-button>
						</view>
					</view>
				</u-popup>
			</u-form-item>

			<u-form-item label-width="150" label="设备号" required borderBottom>
				<u--input v-model="deviceNo" input-align="right" disabled disabledColor="#ffffff" border="none">
				</u--input>
			</u-form-item>

			<u-form-item label-width="150" label="设备类型" required borderBottom @click="deviceTypeSelect">
				<u--input v-model="form.deviceTypeName" input-align="right" disabled disabledColor="#ffffff"
					placeholder="请选择设备类型" border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>

				<u-picker :show="deviceTypeSelectIsShow" :columns="deviceTypeColumns" keyName="deviceTypeName"
					:defaultIndex='[deviceTypeSelectIndex]' @confirm="deviceTypeConfirm" @cancel="deviceTypeSelect"
					@close="deviceTypeSelect">
				</u-picker>
			</u-form-item>

			<u-form-item label-width="70" label="备注名称" borderBottom rightIcon="question-circle"
				right-icon="arrow-right">
				<view class="icon-input-box">
					<u-icon name="question-circle" size="20" @click="showRemarkNameTipModel()"></u-icon>
					<u--input v-model="form.remarkName" input-align="right" maxlength="20" placeholder="输入方便记忆的名称"
						border="none"></u--input>
				</view>
			</u-form-item>

			<view v-if="form.deviceTypeId != deviceTypeEnum.CONVERTIBLE_CURRENCY_MACHINE
				&& form.deviceTypeId != deviceTypeEnum.SUPER_MONEY_CHANGER
				&& form.deviceTypeId != deviceTypeEnum.VENDING_MACHINE
				&& form.deviceTypeId != deviceTypeEnum.SCREEN_VENDING_MACHINE
				&& form.deviceTypeId != deviceTypeEnum.OPEN_DOOR_VENDING_MACHINE
				&& form.deviceTypeId != deviceTypeEnum.BLEND_VENDING_MACHINE">
				<view class="u-p-t-30 u-font-26">
					<text>设备编号</text>
					<text class="u-m-l-10 help">(为方便管理，如：1号机，编号不可以重复)</text>
				</view>
				<view class="example flex u-p-t-30">
					<view class="flex">
						<view class="sm-rectangle used"></view>
						<view class="u-font-24">已使用</view>
					</view>
					<view class="flex">
						<view class="sm-rectangle unused"></view>
						<view class="u-font-24">未使用</view>
					</view>
					<view class="flex">
						<view class="sm-rectangle current"></view>
						<view class="u-font-24">当前选中</view>
					</view>
				</view>

				<view class="grid-number">
					<view class="big-rectangle-box">
						<view v-for="(item,index) in aliasList" @click="aliasChange(item, index)" :key="index">
							<view class="big-rectangle"
								:class="[item.used == 1 ? 'used' : 'unused', alisaIndex == index ? 'current' : '']">
								{{index+1}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</u-form>

		<view class="footer" id="footer">
			<view class="u-p-b-20 u-m-l-30 u-m-r-30">
				<u-button shape="circle" type="primary" @click="save()" color="rgb(96,114,255);">绑&nbsp;&nbsp;定
				</u-button>
			</view>
		</view>

		<u-modal :show="notMerchantStoreIsShow" content="" :showCancelButton="notMerchantStoreShowCancelButton"
			cancelText="关闭" confirm-text="创建场地" @cancel="notMerchantStoreIsShow=false" @confirm="confirm()">.
		</u-modal>

		<u-modal :show="showRemarkNameTip" content="例如：1号_售货机_80000001在某些场景不方便记忆，可以将设备备注为“xx广场二楼B扶梯1号售货机”"
			confirm-text="确定" @confirm="showRemarkNameTip=false" @cancel="showRemarkNameTip=false" />

	</view>
</template>

<script>
	export default {
		data() {
			return {
				slotRight: true,

				deviceNo: '',
				productId: '',

				device: {},
				form: {
					deviceTypeId: '',
					deviceTypeName: '',
					rateEach: 1,
					gameTime: 10,
					storeName: '',
					merchantStoreId: '',
					goodsId: '',
					goodsName: '',
					remarkName: '',
					chargingPileRateId: null,
					chargingPileRateTitle: null,
				},
				merchantStoreList: [],
				merchantStoreSelectIsShow: false,
				deviceTypeList: [],
				deviceTypeColumns: [],
				deviceTypeSelectIndex: 0,
				aliasList: [],
				deviceTypeSelectIsShow: false,
				dfAry: [0],
				alisaIndex: -1,
				notMerchantStoreContent: '当前没有经营场地，请先去创建场地。否则无法绑定设备。',
				height: 0,

				notMerchantStoreShowCancelButton: true,
				notGoodsShowCancelButton: true,
				// 选中绑定的礼品
				bindingGoodsList: [],
				currentBindingGoodsTitle: '已绑定 0 个礼品',
				currentBindingGoodsSum: 0,

				showRemarkNameTip: false,
				defaultMerchantStoreIndex: 0,
				merchantStoreName: '',

				deviceTypeEnum: this.$deviceTypeEnum,
				measuringUnit: '币',
				storageKeyEnum: this.$storageKeyEnum,
			};
		},
		onShow() {
			this.initData();
			this.findAllMerchantStoreByUserId();
		},
		onLoad(option) {
			this.deviceNo = option.deviceNo;
			uni.removeStorageSync(this.storageKeyEnum.twisted_egg_bindingGoodsList);
		},
		onReady() {
			this.getPomHeight();
		},
		methods: {
			setChargingPileRate(data) {
				this.form.chargingPileRateId = data.chargingPileRateId
				this.form.chargingPileRateTitle = data.chargingPileRateTitle
			},

			// 获取各个盒子的高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#footer').boundingClientRect()
				query.exec(res => {
					this.height = wx.getSystemInfoSync().windowHeight;
					for (var i = 0; i < res.length; i++) {
						this.height -= res[i].height;
					}
				});
			},
			showRemarkNameTipModel() {
				this.showRemarkNameTip = true;
			},

			findOneDeviceByDeviceNo() {
				let param = {
					deviceNo: this.deviceNo,
					deviceTypeId: this.form.deviceTypeId,
					productId: this.productId

				}
				this.$api('device.findOneDeviceByDeviceNo', param)
					.then(res => {
						if (res.status == 0) {
							this.device = res.data;
							if (this.device.productId) {
								this.productId = this.device.productId;
							}
							if (!this.$u.test.isEmpty(this.device.deviceTypeId) && !this.$u.test.isEmpty(this
									.deviceTypeList)) {
								for (let i = 0; i < this.deviceTypeList.length; i++) {
									if (this.deviceTypeList[i].id === this.device.deviceTypeId) {
										this.deviceTypeSelectIndex = i;
										this.form.deviceTypeName = this.deviceTypeList[i].deviceTypeName;
										this.form.deviceTypeId = this.deviceTypeList[i].id;
										break;
									}
								}
							} else if (this.device.isBluetooth) {
								this.form.deviceTypeName = '开门式售货机'
								this.form.deviceTypeId = this.deviceTypeEnum.OPEN_DOOR_VENDING_MACHINE
							}
						} else {
							this.$helpers.toast('请求数据失败:' + res.msg);
						}
					})
			},

			save() {
				if (this.$u.test.isEmpty(this.form.merchantStoreId) || this.form.merchantStoreId.length == 0) {
					this.$helpers.toast('请选择经营场地');
					return;
				}
				if (this.$u.test.isEmpty(this.deviceNo) || this.deviceNo.length == 0) {
					this.$helpers.toast('设备号有误，请联系平台');
					return;
				}
				if (this.$u.test.isEmpty(this.form.deviceTypeId) || this.form.deviceTypeId.length == 0) {
					this.$helpers.toast('请选择设备类型');
					return;
				}
				
				if ((this.alisaIndex == null || this.alisaIndex < 0) && (this.form.deviceTypeId != this.deviceTypeEnum
						.CONVERTIBLE_CURRENCY_MACHINE &&
						this.form.deviceTypeId != this.deviceTypeEnum.SUPER_MONEY_CHANGER &&
						this.form.deviceTypeId != this.deviceTypeEnum.VENDING_MACHINE &&
						this.form.deviceTypeId != this.deviceTypeEnum.SCREEN_VENDING_MACHINE &&
						this.form.deviceTypeId != this.deviceTypeEnum.OPEN_DOOR_VENDING_MACHINE &&
						this.form.deviceTypeId != this.deviceTypeEnum.BLEND_VENDING_MACHINE)) {
					this.$helpers.toast('请选择设备编号');
					return;
				}

				uni.showLoading({
					mask: true,
					title: '绑定中，请稍等'
				})
				
				var newBindingGoodsList = [];
				this.bindingGoodsList.forEach(item => {
					// console.info(item)
					if (item.commodityId != null) {
						newBindingGoodsList.push(item)
					}
				})

				if (this.$u.test.isEmpty(this.form.remarkName)) {
					this.form.remarkName = this.$u.trim(this.form.remarkName, 'all')
				}
				let flag = true;
				if (this.form.deviceTypeId == this.deviceTypeEnum.CONVERTIBLE_CURRENCY_MACHINE ||
					this.form.deviceTypeId == this.deviceTypeEnum.SUPER_MONEY_CHANGER ||
					this.form.deviceTypeId == this.deviceTypeEnum.VENDING_MACHINE ||
					this.form.deviceTypeId == this.deviceTypeEnum.OPEN_DOOR_VENDING_MACHINE ||
					this.form.deviceTypeId == this.deviceTypeEnum.BLEND_VENDING_MACHINE) {
					flag = false;
				}
				let param = {
					deviceNo: this.deviceNo,
					deviceTypeId: this.form.deviceTypeId,
					merchantStoreId: this.form.merchantStoreId,
					rateEach: this.form.rateEach,
					alias: flag ? this.alisaIndex + 1 : '',
					commodityDtoList: newBindingGoodsList,
					remarkName: this.form.remarkName,
					chargingPileRateId: this.form.chargingPileRateId,
					gameTime: this.form.gameTime,
				}

				this.$api('device.updateBindDeviceByMerchantStoreId', param).then(res => {
					if (res.status == 0) {
						uni.removeStorageSync(this.storageKeyEnum.twisted_egg_bindingGoodsList);
						this.$helpers.toast('绑定成功', 'success', 3000, true, () => {
							uni.showModal({
								title: '提示',
								content: '是否继续绑定设备？',
								cancelText: '取消',
								confirmText: '继续绑定',
								showCancel: true,
								success(res) {
									if (res.confirm) {
										uni.navigateBack({
											delta: 1
										});
									} else {
										uni.switchTab({
											url: '/pages/home/home',
											success() {
												uni.navigateTo({
													url: '/pages-device/device-manage/device-manage'
												})
											}
										})
									}
								}
							});
						});
					} else {
						uni.hideLoading();
						this.$helpers.toast('绑定失败：' + res.msg);
					}
				})
			},
			merchantStoreChange(index) {
				this.merchantStoreName = this.merchantStoreList[index].storeName;
				this.defaultMerchantStoreIndex = index;

			},
			merchantStoreConfirm() {

				this.alisaIndex = -1;
				this.form.merchantStoreId = this.merchantStoreList[this.defaultMerchantStoreIndex].id;
				this.form.storeName = this.merchantStoreList[this.defaultMerchantStoreIndex].storeName;
				this.measuringUnit = this.merchantStoreList[this.defaultMerchantStoreIndex].measuringUnit;
				// console.log("this.measuringUnit", this.merchantStoreList[this.defaultMerchantStoreIndex])
				this.merchantStoreSelectIsShow = false;
				this.findAllDeviceByCondition();
			},

			// 展示场地列表
			showMerchantStorePicker() {
				if (this.merchantStoreList.length == 0) {
					this.merchantStoreNotFound();
					return
				}

				this.merchantStoreSelectIsShow = true;
			},

			deviceTypeSelect() {
				this.deviceTypeSelectIsShow = !this.deviceTypeSelectIsShow;
			},
			deviceTypeConfirm(e) {
				this.form.deviceTypeId = e.value[0].id;
				this.form.deviceTypeName = e.value[0].deviceTypeName;

				uni.removeStorageSync(this.storageKeyEnum.twisted_egg_bindingGoodsList);
				this.initData();

				for (var i = 0; i < this.deviceTypeList.length; i++) {
					if (e.value[0] == this.deviceTypeList[i].id) {
						this.deviceTypeSelectIndex = i;
						return;
					}
				}

				this.deviceTypeSelect();

			},

			goodsSelect() {
				if (this.$u.test.isEmpty(this.form.deviceTypeId)) {
					this.$helpers.toast('请选择设备类型');
					return;
				}

				if (this.device == null || this.device.id == null || this.device.id == 0) {
					this.$helpers.toast('设备参数有误');
					return;
				}

				uni.navigateTo({
					url: "/pages-device/twisted-egg/twisted-egg?from=facility&deviceId=" + this.device.id +
						'&deviceTypeId=' + this.form.deviceTypeId +
						'&pulseSwitchState=' + this.device.pulseSwitchState
				});
			},

			aliasChange(item, index) {
				if (item.used == 1) {
					this.$helpers.toast('该编号已被使用啦');
					return;
				} else if (this.alisaIndex == index) {
					this.alisaIndex = -1
				} else if (item.unused == 1) {
					this.alisaIndex = index;
				}
			},

			initData() {
				try {
					const value = uni.getStorageSync(this.storageKeyEnum.twisted_egg_bindingGoodsList);
					// console.log("bindingGoodsList:");
					// console.log(value);
					this.currentBindingGoodsSum = 0;
					if (Array.isArray(value)) {
						this.bindingGoodsList = value;
						for (let i = 0; i < this.bindingGoodsList.length; i++) {
							// console.log("i:" + i);
							if (!this.$u.test.isEmpty(this.bindingGoodsList[i].commodityId)) {
								// console.log("i:" + i);
								this.currentBindingGoodsSum++;
								// console.log("i_this.currentBindingGoodsSum:" + this.currentBindingGoodsSum);
							}
						}
					}
				} catch (e) {
					console.error(e.toString())
				}
				this.currentBindingGoodsTitle = '已绑定 ' + this.currentBindingGoodsSum + ' 个礼品'
				// console.log("currentBindingGoodsTitle:" + this.currentBindingGoodsTitle);

				this.findAllDeviceType();
			},

			findAllMerchantStoreByUserId() {
				this.$api('merchantStore.findAllMerchantStoreByUserId', null).then(res => {
					if (res.status == 0) {
						if (res.data.length > 0) {
							this.merchantStoreList = res.data;

							for (let i = 0; i < this.merchantStoreList.length; i++) {
								const merchantStore = this.merchantStoreList[i];
								if (merchantStore.defaultStatus) {
									this.merchantStoreName = merchantStore.storeName;
									this.defaultMerchantStoreIndex = i;
									this.form.merchantStoreId = merchantStore.id;
									this.form.storeName = merchantStore.storeName;
									this.measuringUnit = merchantStore.measuringUnit;
									this.findAllDeviceByCondition();
									break;
								}
							}

							if (this.merchantStoreList.length == 1 && this.$u.test.isEmpty(this.form
									.merchantStoreId)) {
								this.form.merchantStoreId = this.merchantStoreList[0].id;
								this.form.storeName = this.merchantStoreList[0].storeName;
							}
						} else {
							uni.hideLoading();
							this.merchantStoreNotFound();
						}
					} else {
						uni.hideLoading();
						this.$helpers.toast('获取数据失败：' + res.msg);
					}
				})
			},

			// 暂无场地，提示创建场地
			merchantStoreNotFound() {
				uni.showModal({
					title: '',
					content: '当前没有经营场地，请先去创建场地。否则无法绑定设备',
					success(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages-other/merchant-store/add-merchant-store?from=deviceRegisterV2&siteId=0'
							})
						}
					}
				});
			},
			navToStoreManage() {
				uni.navigateTo({
					url: '/pages-other/merchant-store/add-merchant-store?from=deviceRegisterV2&siteId=0'
				})
			},
			findAllDeviceType() {
				uni.showLoading({
					mask: true,
					title: '加载中~'
				})

				this.$api('deviceType.findAllDeviceType', null).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						this.deviceTypeList = res.data;
						this.deviceTypeColumns = []
						this.deviceTypeColumns.push(this.deviceTypeList)
						this.findOneDeviceByDeviceNo();
					} else {
						this.$helpers.toast('获取数据失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},

			findAllDeviceByCondition() {
				let params = {
					merchantStoreId: this.form.merchantStoreId
				}
				this.$api('device.findAllDeviceByCondition', params).then(res => {
					if (res.status == 0) {
						let deviceList = res.data;

						var deviceListMap = new Map();
						for (let i = 0; i < deviceList.length; i++) {
							deviceListMap.set(deviceList[i].alias, deviceList[i].alias);
						}

						this.aliasList = [];
						let i = 0;
						let count = 20;
						let min = 5;
						for (let j = 1; j <= count; j++) {
							if (deviceListMap.get(j) == j) {
								this.aliasList.push({
									used: 1,
									unused: 0
								});
							} else {
								i++;
								this.aliasList.push({
									used: 0,
									unused: 1
								});
							}
							// 编号小于min个时在加min个
							if (j == count) {
								if (i < min) {
									count += min;
								}
							}
						}
					} else {
						uni.hideLoading();
						this.$helpers.toast('获取数据失败：' + res.msg);
					}
				})
			},

			reachBottom() {
				if (this.status == 'nomore') {
					return;
				}
				this.status = 'loading';
				this.findAllMerchantStoreByUserId();
			},
			close() {
				this.merchantStoreSelectIsShow = false;
			},
		}
	}
</script>


<style lang="scss">
	page {
		background-color: #FFFFFF;
	}

	.content {
		position: relative;
	}

	.from {
		border-radius: 20rpx;
		// padding: $u-margin-medium;

	}

	.help {
		font-size: 24rpx;
		color: rgba(0, 0, 0, 0.5);
	}

	.example {
		margin: 0 20rpx;
	}

	.goods:after {
		border: 0;
	}

	.flex {
		display: flex;
		justify-content: space-between;
		align-items: center;


		.sm-rectangle {
			margin-right: 10rpx;
			border-radius: 10rpx;
			width: 30rpx;
			height: 30rpx;
		}

	}

	.grid-number {
		margin: 50rpx 20rpx 0;

		.big-rectangle {
			text-align: center;
			margin: 20rpx 10rpx 20rpx 0;
			border-radius: 10rpx;
			width: 62rpx;
			height: 62rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 30rpx 30rpx;
			color: rgba(0, 0, 0, 0.8);
			font-size: $f-base;
		}
	}

	.used {
		border: 1rpx solid rgb(223, 230, 246);
		background-color: rgb(223, 230, 246);
		color: #FFF !important;
	}

	.unused {
		border: 1rpx solid rgb(212, 212, 212);
		background-color: #FFF;
	}

	.current {
		border: 1rpx solid rgb(96, 114, 255);
		background: rgb(96, 114, 255);
		color: #FFF !important;
	}

	/deep/ .u-form-item--right__content__slot {
		justify-content: flex-end;
	}

	.slot-content {
		padding: $u-padding-large;
		text-align: left;
	}

	.general {
		z-index: 1000;
	}

	.number-box {
		display: flex;
		justify-content: flex-end;
	}

	.footer {
		margin-top: 30rpx;
	}

	.big-rectangle-box {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}


	.icon-input-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.flex {
		display: flex;
	}

	.select-store-title {
		text-align: center;
		font-size: 32rpx;
		margin-bottom: 10rpx;
	}

	.model-item {
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.model-set {
		display: flex;
		align-items: center;
		font-size: $f-base;
		padding: 25rpx 20rpx;
	}

	/deep/ .u-form-item__body {
		padding: 30rpx 0 !important;
	}

	/deep/ .u-input__content__field-wrapper__field {
		font-size: $f-base !important;
	}

	/deep/ .u-radio {
		margin-bottom: 40rpx;
	}
</style>